package com.data.springbootdynamicdata.config;

import com.data.springbootdynamicdata.datasource.DataSourceContextHolder;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;

/***
 *  Created with IntelliJ IDEA.
 *  Author:  wenlin
 *  Date:  2018/3/29 9:39
 *  Description:
 **/
@Aspect
@Component
public class OperateAspect {

    @Pointcut("@annotation(SetTargetDateSource))")
    public void annotationPointCut() {

    }


    @Before("annotationPointCut()")
    public void before(JoinPoint joinPoint){

        MethodSignature sign =  (MethodSignature)joinPoint.getSignature();

        //Method method = sign.getMethod();

        if(joinPoint.getArgs()!=null&&joinPoint.getArgs().length>0) {
            String source = (String) joinPoint.getArgs()[0];
            //切换数据源
            DataSourceContextHolder.setDBType(source);

            System.out.println("打印：" + DataSourceContextHolder.getDBType() + " 数据源");
        }
    }
    @After("annotationPointCut()")
    public void after(JoinPoint joinPoint){
        MethodSignature sign =  (MethodSignature)joinPoint.getSignature();

        //Method method = sign.getMethod();

        DataSourceContextHolder.clearDBType();

        System.out.println("打印："+DataSourceContextHolder.getDBType()+" 数据源");
        System.out.println("===========任务执行完毕=============");
    }
}
